package com.wjs.juc.LockSupport;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

public class LockSupportDemo1 {
    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+" come in");
            LockSupport.park();
            System.out.println(Thread.currentThread().getName()+":通行");
        }, "t1");
        t1.start();
        TimeUnit.SECONDS.sleep(2);
        new Thread(()->{
            LockSupport.unpark(t1);
            System.out.println(Thread.currentThread().getName()+"发出了通知");
        },"t2").start();
    }

    /**
     * lock实现线程之间通行
     * @throws InterruptedException
     */
    private static void ByLocked() throws InterruptedException {
        ReentrantLock lock=new ReentrantLock();
        Condition condition = lock.newCondition();
        new Thread(()->{
                lock.lock();
                System.out.println(Thread.currentThread().getName()+"come in");
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"完成");
                lock.unlock();

        },"t1").start();
        TimeUnit.SECONDS.sleep(2);
        new Thread(()->{
            lock.lock();
            condition.signal();
                System.out.println(Thread.currentThread().getName()+"发出了通知");
            lock.unlock();
        },"t2").start();
    }

    /**
     * synchronized实现线程间通信
     * @throws InterruptedException
     */
    private static void BySynchronized() throws InterruptedException {
        Object lock=new Object();
        new Thread(()->{
            synchronized (lock){
                System.out.println(Thread.currentThread().getName()+"come in");
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"完成");
            }
        },"t1").start();
        TimeUnit.SECONDS.sleep(2);
        new Thread(()->{
            synchronized (lock){
                lock.notify();
                System.out.println(Thread.currentThread().getName()+"发出了通知");
            }
        },"t2").start();
    }
}
